package com.tree.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tree.backend.entity.dto.DemandAuditDTO;
import com.tree.backend.entity.dto.DemandDTO;
import com.tree.backend.entity.dto.DemandQueryDTO;
import com.tree.backend.entity.pojo.Demand;
import com.tree.backend.entity.pojo.User;
import com.tree.backend.entity.vo.DemandListVO;
import com.tree.backend.entity.vo.DemandStatsVO;
import com.tree.backend.entity.vo.DemandVO;
import com.tree.backend.entity.vo.EnterpriseVO;
import com.tree.backend.mapper.DemandOrderMapper;
import com.tree.backend.mapper.EnterpriseMapper;
import com.tree.backend.entity.pojo.DemandOrder;
import com.tree.backend.entity.pojo.Enterprise;
import com.tree.backend.exception.GlobalException;
import com.tree.backend.mapper.DemandMapper;
import com.tree.backend.mapper.UserMapper;
import com.tree.backend.service.IDemandService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tree.backend.utils.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 需求表 服务实现类
 * </p>
 *
 * @author tree
 * @since 2025-11-06
 */
@Service
@RequiredArgsConstructor
public class DemandServiceImpl extends ServiceImpl<DemandMapper, Demand> implements IDemandService {

    private final UserMapper userMapper;
    private final EnterpriseMapper enterpriseMapper;
    private final DemandOrderMapper demandOrderMapper;

    private static final Map<Integer, String> STATUS_MAP = new HashMap<Integer, String>() {
        {
            put(0, "待审核");
            put(1, "审核通过");
            put(2, "审核拒绝");
            put(3, "已发布");
            put(4, "已接单");
            put(5, "进行中");
            put(6, "已完成");
            put(7, "已关闭");
        }
    };

    @Override
    public Page<DemandListVO> getDemandList(DemandQueryDTO queryDTO) {
        Page<Demand> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        QueryWrapper<Demand> queryWrapper = new QueryWrapper<>();
        
        // 按标题模糊查询
        if (queryDTO.getTitle() != null && !queryDTO.getTitle().isEmpty()) {
            queryWrapper.like("title", queryDTO.getTitle());
        }
        
        // 按状态筛选
        if (queryDTO.getStatus() != null) {
            queryWrapper.eq("status", queryDTO.getStatus());
        }
        
        // 按预算范围筛选
        if (queryDTO.getMinBudget() != null) {
            queryWrapper.ge("budget", queryDTO.getMinBudget());
        }
        if (queryDTO.getMaxBudget() != null) {
            queryWrapper.le("budget", queryDTO.getMaxBudget());
        }

        // 按用户ID筛选，普通用户只能查看自己的需求
        // 使用UserContext获取当前登录用户ID，不依赖前端传递的参数
        Long currentUserId = UserContext.getCurrentUserId();
        if (currentUserId != null) {
            // 假设用户类型1是普通用户
            Integer userType = UserContext.getCurrentUserType();
            if (userType != null && userType == 1) {
                queryWrapper.eq("user_id", currentUserId);
            }
        }

        // 按创建时间降序排序
        queryWrapper.orderByDesc("create_time");
        
        // 分页查询
        Page<Demand> demandPage = this.page(page, queryWrapper);


        // 转换为VO对象
        Page<DemandListVO> resultPage = new Page<>(page.getCurrent(), page.getSize());
        resultPage.setTotal(demandPage.getTotal());
        
        List<DemandListVO> voList = demandPage.getRecords().stream().map(demand -> {
            DemandListVO vo = new DemandListVO();
            vo.setId(demand.getId());
            vo.setTitle(demand.getTitle());
            vo.setUserId(demand.getUserId());
            User user = userMapper.selectById(demand.getUserId());
            if (user != null) {
                vo.setUserName(user.getRealName());
            }
            vo.setDescription(demand.getDescription());
            vo.setBudget(demand.getBudget());
            vo.setDeadline(demand.getDeadline());
            vo.setStatus(demand.getStatus());
            vo.setStatusText(getStatusText(demand.getStatus()));
            vo.setPublishTime(demand.getPublishTime());
            vo.setAuditRemark(demand.getAuditRemark());
            return vo;
        }).collect(Collectors.toList());
        
        resultPage.setRecords(voList);
        return resultPage;
    }

    @Override
    public DemandVO getDemandDetail(Long id) {
        Demand demand = this.getById(id);
        if (demand == null) {
            throw new GlobalException(404, "需求不存在");
        }
        
        DemandVO vo = new DemandVO();
        vo.setId(demand.getId());
        vo.setUserId(demand.getUserId());
        vo.setUserName(userMapper.selectById(demand.getUserId()).getRealName());
        vo.setTitle(demand.getTitle());
        vo.setDescription(demand.getDescription());
        vo.setBudget(demand.getBudget());
        vo.setDeadline(demand.getDeadline());
        vo.setStatus(demand.getStatus());
        vo.setStatusText(getStatusText(demand.getStatus()));
        vo.setAuditRemark(demand.getAuditRemark());
        vo.setAuditTime(demand.getAuditTime());
        vo.setPublishTime(demand.getPublishTime());
        vo.setCreateTime(demand.getCreateTime());
        
        return vo;
    }

    @Override
    public Demand addDemand(DemandDTO demandDTO, Long userId, Integer userType) {
        Demand demand = new Demand();
        demand.setUserId(userId);
        demand.setUserType(userType);
        demand.setTitle(demandDTO.getTitle());
        demand.setDescription(demandDTO.getDescription());
        demand.setBudget(demandDTO.getBudget());
        demand.setDeadline(demandDTO.getDeadline());
        demand.setStatus(0); // 新增的需求默认为待审核状态
        demand.setCreateTime(LocalDateTime.now());
        demand.setUpdateTime(LocalDateTime.now());
        
        this.save(demand);
        return demand;
    }

    @Override
    public Demand updateDemand(Long id, DemandDTO demandDTO) {
        Demand demand = this.getById(id);
        if (demand == null) {
            throw new GlobalException(404, "需求不存在");
        }
        demand.setTitle(demandDTO.getTitle());
        demand.setDescription(demandDTO.getDescription());
        demand.setBudget(demandDTO.getBudget());
        demand.setDeadline(demandDTO.getDeadline());
        demand.setUpdateTime(LocalDateTime.now());
        demand.setAuditRemark(demandDTO.getAuditRemark());
        this.updateById(demand);
        return demand;
    }

    @Override
    public void deleteDemand(Long id) {
        Demand demand = this.getById(id);
        if (demand == null) {
            throw new GlobalException(404, "需求不存在");
        }

        this.removeById(id);
    }

    @Override
    public void auditDemand(Long id, DemandAuditDTO auditDTO, Long auditUserId) {
        Demand demand = this.getById(id);
        if (demand == null) {
            throw new GlobalException(404, "需求不存在");
        }
        
        // 只有待审核状态可以审核
        if (demand.getStatus() != 0) {
            throw new GlobalException(400, "只有待审核的需求可以审核");
        }
        
        // 审核拒绝时必须有审核备注
        if (auditDTO.getStatus() == 2 && (auditDTO.getAuditRemark() == null || auditDTO.getAuditRemark().isEmpty())) {
            throw new GlobalException(400, "审核拒绝时必须填写审核备注");
        }
        
        demand.setStatus(auditDTO.getStatus());
        demand.setAuditRemark(auditDTO.getAuditRemark());
        demand.setAuditTime(LocalDateTime.now());
        demand.setAuditUserId(auditUserId);
        
        // 审核通过时设置发布时间并设置为已发布
        if (auditDTO.getStatus() == 1) {
            demand.setPublishTime(LocalDateTime.now());
            demand.setStatus(3);
        }
        
        this.updateById(demand);
    }

    @Override
    public DemandStatsVO getDemandStats() {
        DemandStatsVO statsVO = new DemandStatsVO();
        
        // 总需求数
        statsVO.setTotalCount((int) this.count());
        
        // 待审核需求数
        statsVO.setPendingAuditCount((int) this.count(new QueryWrapper<Demand>().eq("status", 0)));
        
        // 已发布需求数
        statsVO.setPublishedCount((int) this.count(new QueryWrapper<Demand>().eq("status", 3)));
        
        // 进行中需求数
        statsVO.setInProgressCount((int) this.count(new QueryWrapper<Demand>().eq("status", 5)));
        
        // 已完成需求数
        statsVO.setCompletedCount((int) this.count(new QueryWrapper<Demand>().eq("status", 6)));
        
        return statsVO;
    }

    @Override
    public String getStatusText(Integer status) {
        return STATUS_MAP.getOrDefault(status, "未知状态");
    }

    @Override
    public List<EnterpriseVO> getPotentialEnterprises(Long demandId) {
        // 验证需求是否存在且状态为已发布
        Demand demand = this.getById(demandId);
        if (demand == null) {
            throw new GlobalException(404, "需求不存在");
        }
        if (demand.getStatus() != 3) {
            throw new GlobalException(400, "只有已发布的需求可以查看接单企业");
        }

        // 查询所有愿意接单的企业（这里简化处理，实际应该从需求接单表中查询）
        // 这里我们模拟从企业表中查询所有企业
        List<Enterprise> enterprises = enterpriseMapper.selectList(null);
        
        // 转换为VO对象
        return enterprises.stream().map(enterprise -> {
            EnterpriseVO vo = new EnterpriseVO();
            vo.setId(enterprise.getId());
            vo.setName(enterprise.getName());
            vo.setDescription(enterprise.getDescription());
            vo.setContactName(enterprise.getContactName());
            vo.setContactPhone(enterprise.getContactPhone());
            vo.setContactEmail(enterprise.getContactEmail());
            vo.setStatus(enterprise.getStatus());
            // 可以添加一个额外的字段来存储报价信息
            // 实际项目中应该从需求接单表中查询真实报价
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean selectEnterprise(Long demandId, Long enterpriseId) {
        // 验证需求是否存在且状态为已发布
        Demand demand = this.getById(demandId);
        if (demand == null) {
            throw new GlobalException(404, "需求不存在");
        }
        if (demand.getStatus() != 3) {
            throw new GlobalException(400, "只有已发布的需求可以选择接单企业");
        }

        // 验证企业是否存在
        Enterprise enterprise = enterpriseMapper.selectById(enterpriseId);
        if (enterprise == null) {
            throw new GlobalException(404, "企业不存在");
        }

        // 开启事务（这里简化处理，实际应该使用@Transactional注解）
        try {
            // 更新需求状态为已接单
            demand.setStatus(4);
            demand.setUpdateTime(LocalDateTime.now());
            this.updateById(demand);

            // 创建需求接单记录
            DemandOrder demandOrder = new DemandOrder();
            demandOrder.setDemandId(demandId);
            demandOrder.setEnterpriseId(enterpriseId);
            demandOrder.setUserId(UserContext.getCurrentUserId());
            demandOrder.setBidAmount(demand.getBudget());
            demandOrder.setCreateTime(LocalDateTime.now());
            demandOrder.setUpdateTime(LocalDateTime.now());
            demandOrderMapper.insert(demandOrder);

            return true;
        } catch (Exception e) {
            throw new GlobalException(500, "选择企业接单失败：" + e.getMessage());
        }
    }
}
